<template>
  <view class="page">
    <view style="display: flex;align-items: center;">
      <view class="distance" @click="goMap">{{city?city:'位置'}}</view>
      
      <uni-search-bar style="flex: 1;" v-model="type" @confirm="search" @input="input" ></uni-search-bar>
      
    </view>
    <!-- <view class="distance">选择位置</view> -->
    <slider block-size="12" :value="distance" step="1000" @change="sliderChange" min="0" max="50000" show-value activeColor="#FFCC33" backgroundColor="#000000" block-color="rgb(7, 150, 193)"/>
    <view
    v-for="item,index in list"
    :key="index">
    <view class="item" v-if="ContactList.indexOf(item.business.tel)==-1">
      <view style="margin-bottom: 10rpx;">店名：{{ item.name }}</view>
      <view class="save" v-if="ContactList.indexOf(item.business.tel)!=-1">已保存</view>
      <view style="margin-bottom: 10rpx;">地址：{{ item.address }}</view>
      <view style="margin-bottom: 10rpx;">营业时间：{{ item.business.opentime_today||'无' }}</view>
      <view style="display: flex;justify-content: flex-end;color: rgb(88, 89, 97);">
        {{ item.business.tel }}
        <view @click="call(item.business.tel)" class="call">拨打电话</view>
        <view @click="contact(item)" class="contact">存入联系人</view>
      </view>
    </view>
      
    </view>
    <view class="flxed" @click="addWeChat">
    一键添加
  </view>
  </view>
  
  <citySelect v-if="show" @back_city="back_city" @back="back" />
</template>

<script>
import citySelect from '../../components/components/linzq-citySelect/linzq-citySelect.vue';
export default {
  components:{
    citySelect:citySelect
  },
  data() {
    return {
      show:false,
      list:[],
      ContactList:[],
      num:1,
      type:'餐饮',
      distance:0,
      city:'位置',
      page:1
    };
  },

  mounted() {
   // #ifdef APP-PLUS
    this.getBooks()
    //#endif
    uni.getStorageSync('ContactList')?this.ContactList = uni.getStorageSync('ContactList'):false
    this.getPOI()
  },

  methods: {
    back(){
      this.show = false
    },
    addWeChat(){
      this.list = this.list.filter(e=>this.ContactList.indexOf(e.business.tel)==-1)
      for(let i = 0; i < 10; i++){
        this.contact(this.list[i])
      }
      this.getBooks()

      uni.showToast({title:"保存成功",icon:'none'})
    },
    back_city(e){
      uni.showLoading()
      if(e=='no')return
      uni.request({
        url: `https://restapi.amap.com/v3/place/text?parameters&key=3b302662f1028ff0a78c5950da3fb3fc&keywords=${this.type}&city=${e.cityName}`,
        method: 'GET',
        success: ({ data, statusCode, header }) => {
          uni.hideLoading()
          let poiArr = data.pois
          poiArr = poiArr.filter(e=>e.tel.length&&/^1[3-9]\d{9}$/.test(e.tel))
          poiArr.forEach(e=>{
            e.business={tel:e.tel}
          })
          this.list = poiArr.filter(e=>this.ContactList.indexOf(e.business.tel)==-1)
          if(this.list.length<6){
            this.getCityList()
          }
        },
        fail: (error) => {
          uni.hideLoading()
          console.log(error);
        }
      })
      this.show = false
      this.city = e.cityName
    },
    getCityList(){
      uni.request({
           url: `https://restapi.amap.com/v3/place/text?parameters&key=3b302662f1028ff0a78c5950da3fb3fc&keywords=${this.type}&city=${this.city}&page=${this.page}`,
           method: 'GET',
           success: ({ data, statusCode, header }) => {
             let poiArr = data.pois
             poiArr = poiArr.filter(e=>e.tel.length&&/^1[3-9]\d{9}$/.test(e.tel))
             poiArr.forEach(e=>{
               e.business={tel:e.tel}
             })
             this.list = [...this.list,...poiArr]
             this.page++
             this.list = this.list.filter(e=>this.ContactList.indexOf(e.business.tel)==-1)
             if(this.list.length<6)this.getCityList()
           },
           fail: (error) => {
             console.log(error);
           }
          })
    },
    getBooks(){
      var that = this
      plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE,function(addressbook){
		    console.log('获取通讯录对象成功')
		    console.log(addressbook)
		    addressbook.find(["displayName","phoneNumbers"],function(contacts){
			  console.log("获取联系人成功")
			  console.log(contacts)
        that.ContactList = contacts
        console.log('通讯录数组');
        that.ContactList = that.ContactList.filter(e=>e.phoneNumbers.length)
        that.ContactList = that.ContactList.map(e=>e.phoneNumbers[0].value.replace(/^\+86/, ''))
        console.log(that.ContactList);
		  })
    })
    },
    goMap(){
      // this.$refs.city.open('bottom')
      this.show = true
      // uni.navigateTo({ url: '/pages/index/map' })
    },
    sliderChange(e){
    this.city = '位置'
    this.getPOI()
      this.distance = e.detail.value
    },
    search(){
    if(this.city=='位置'){
      this.getPOI()
    }else{
      uni.request({
        url: `https://restapi.amap.com/v3/place/text?parameters&key=3b302662f1028ff0a78c5950da3fb3fc&keywords=${this.type}&city=${this.city}`,
        method: 'GET',
        success: ({ data, statusCode, header }) => {
          uni.hideLoading()
          let poiArr = data.pois
          poiArr = poiArr.filter(e=>e.tel.length&&/^1[3-9]\d{9}$/.test(e.tel))
          poiArr.forEach(e=>{
            e.business={tel:e.tel}
          })
          this.list = poiArr.filter(e=>this.ContactList.indexOf(e.business.tel)==-1)
          if(this.list.length<6){
            this.getCityList()
          }
        },
        fail: (error) => {
          uni.hideLoading()
          console.log(error);
        }
      })
    }
      
    },
    async getPOI(){
      this.num=1
      let location
      uni.getLocation({
        type: 'gcj02',
        success: async({ longitude, latitude }) => {
          location = `${latitude},${longitude}`
          const res = await uni.request({
        url: `https://restapi.amap.com/v5/place/around?key=3b302662f1028ff0a78c5950da3fb3fc&location=${location}&radius=${this.distance}&keywords=${this.type}&show_fields=business&page_size=25&page_num=${this.num}`,
        method: 'GET'
      })
      if(res.data.status=='0')return uni.showToast({
        title: '请求失败,请重试',
        icon: 'none'
      })
      this.num++
      let poiArr = res.data.pois.filter(e=>{
        return e.business.tel
      })
      poiArr.forEach((e,i) => {
        let reg = /^1[3-9]\d{9}$/
        let str = e.business.tel.split(';')
        let str1 = str.filter(e => reg.test(e))
        if(!str1.length){
          poiArr.splice(i,1)
        }else{
          e.business.tel = str1[0]
        }
      });
      let phone = /^1[3-9]\d{9}$/
      this.list = poiArr.filter(e=>phone.test(e.business.tel))
      console.log(this.list);
      let Oo = 0
      this.list.forEach(e=>{
        if(this.ContactList.indexOf(e.business.tel)!=-1){
          Oo++
        }
      })
      if(this.list.length-Oo<=5){
        this.num++
        this.reach()
      }
      uni.stopPullDownRefresh();
        },
        fail: (error) => {
          console.log(error);
        }
      })
      
    },
    call(tel){
      uni.makePhoneCall({
        phoneNumber: tel,
        success: (result) => {},
        fail: (error) => {
          uni.showToast({
            title: '用户取消',
            icon: 'none',
            mask: true
          })
        }
      })
    },
    reach(){
      console.log('翻页获取');
    let location
      uni.getLocation({
        type: 'gcj02',
        success: async({ longitude, latitude }) => {
          location = `${latitude},${longitude}`
          const res = await uni.request({
        url: `https://restapi.amap.com/v5/place/around?key=3b302662f1028ff0a78c5950da3fb3fc&location=${location}&radius=${this.distance}&keywords=餐饮&show_fields=business&page_size=25&page_num=${this.num}`,
        // url: `https://restapi.amap.com/v5/place/around?key=3b302662f1028ff0a78c5950da3fb3fc&location=116.473168,39.993015&radius=10000&types=011100`,
        method: 'GET'
      })
      this.num++
      let poiArr = res.data.pois.filter(e=>{
        return e.business.tel
      })
      poiArr.forEach((e,i) => {
        let reg = /^1[3-9]\d{9}$/
        let str = e.business.tel.split(';')
        let str1 = str.filter(e => reg.test(e))
        if(!str1.length){
          poiArr.splice(i,1)
        }else{
          e.business.tel = str1[0]
        }
      });
      let phone = /^1[3-9]\d{9}$/
      poiArr = poiArr.filter(e=>phone.test(e.business.tel))
      this.list = [...this.list,...poiArr]
      let Oo = 0
      this.list.forEach(e=>{
        if(this.ContactList.indexOf(e.business.tel)!=-1){
          Oo++
        }
      })
      if(this.list.length-Oo<=5){
        this.num++
        this.reach()
      }
      uni.stopPullDownRefresh();
      console.log(this.list);
        },
        fail: (error) => {
          console.log(error);
        }
      })
  },
    contact(e){
      uni.addPhoneContact({
	      firstName: e.name,
	      mobilePhoneNumber: e.business.tel,
	      weChatNumber: e.business.tel,
        success: (result) => {
          this.getBooks()
          uni.showToast({title:"保存成功",icon:'none'})
          // this.list.forEach((e,i)=>{
          //   if(this.ContactList.indexOf(e.business.tel)!=-1){
          //     console.log(e.name,i);
          //     this.list.splice(i,1)
          //     this.list.push(e)
          //    }
          // })
          uni.setStorageSync('ContactList',this.ContactList)
        },
        fail: (error) => {
          console.log(error);
          wx.authorize({
            scope:'scope.addPhoneContact',
            success: (result)=>{
              console.log('授权成功');
            },
          });
        }
      })
    }
  },
  async onPullDownRefresh(){
    if(this.city=='位置'){
      this.getPOI()
    }else{
      this.getCityList()
    }
  },
  

  onReachBottom(){
    
    if(this.city=='位置'){
      this.reach()
    }else{
      this.getCityList()
    }

  }
};
</script>

<style lang="scss" scoped>
  .page{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 30rpx;
    box-sizing: border-box;
    .flxed{
      position: fixed;
      right: 12rpx;
      bottom: 100rpx;
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      background-color: rgb(6, 180, 128);
      font-size: 24rpx;
      color: #fff;
      text-align: center;
      line-height: 120rpx;
    }
    .distance{
      // display: flex;
      // justify-content: flex-end;
      font-size: 28rpx;
      color: rgb(144, 147, 153);
      // margin-bottom: 20rpx;
      width: 90rpx;
    }
    .item{
      position: relative;
      font-size: 26rpx;
      padding: 30rpx;
      box-sizing: border-box;
      background-color: rgb(249,249,249);
      // background-color: pink;
      border-radius: 60rpx;
      margin-bottom: 30rpx;
      .save{
        position: absolute;
        top: 20rpx;
        right: 30rpx;
        color:rgb(244, 82, 82);
      }
      .call{
        width: 110rpx;
        height: 40rpx;
        margin: 0 20rpx;
        background-color: rgb(7, 150, 193);
        color: #fff;
        padding: 0 6rpx;
        line-height: 40rpx;
        text-align: center;
        font-size: 24rpx;
        border-radius: 18rpx;
      }
      .contact{
        width: 130rpx;
        height: 40rpx;
        margin: 0 20rpx;
        background-color: rgb(7, 150, 193);
        color: #fff;
        padding: 0 6rpx;
        line-height: 40rpx;
        text-align: center;
        font-size: 24rpx;
        border-radius: 18rpx;
        margin: 0;
      }
    }
  }
  .slider{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 670rpx;
    height: 100rpx; 
    background-color: #fff;
    border-radius: 20rpx;
  }

  .city{
    background-color: #fff;

  }
</style>
